package com.fr.web.core.service;

import com.fr.base.FRContext;
import com.fr.base.core.util.vt.VT4FR;
import com.fr.base.core.util.vt.VT4FR.FUNC;
import com.fr.base.file.ClusterConfigManager;
import com.fr.base.file.ConfigManager;
import com.fr.util.Utils;
import com.fr.web.cluster.ClusterService;
import com.fr.web.core.WebUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class ClusterUtilService extends NoSessionIDService
{
  private static ClusterUtilService CLUSTERUTIL_SERVICE = new ClusterUtilService();

  public static ClusterUtilService getInstance()
  {
    return CLUSTERUTIL_SERVICE;
  }

  public boolean accept(String paramString)
  {
    return (("cluster_test_all".equals(paramString)) || ("cluster_test".equals(paramString)) || ("test_cluster".equals(paramString)));
  }

  public void process(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, String paramString)
    throws Exception
  {
    if ("cluster_test_all".equals(paramString))
      ClusterTestAll(paramHttpServletRequest, paramHttpServletResponse);
    else if ("cluster_test".equals(paramString))
      clusterTest(paramHttpServletRequest, paramHttpServletResponse);
    else if ("test_cluster".equals(paramString))
      reClusterTest(paramHttpServletRequest, paramHttpServletResponse);
  }

  private static void doRedirect(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, ClusterService paramClusterService1, ClusterService paramClusterService2)
    throws IOException
  {
    PostMethod localPostMethod = createMethod(paramHttpServletRequest, paramClusterService1, paramClusterService2);
    HttpClient localHttpClient = new HttpClient();
    int i = localHttpClient.executeMethod(localPostMethod);
    if (i != 200)
      FRContext.getLogger().log(Level.WARNING, "Cluster Redirect Method failed: " + localPostMethod.getStatusLine());
    try
    {
      Header[] arrayOfHeader = localPostMethod.getResponseHeaders();
      for (int j = 0; j < arrayOfHeader.length; ++j)
        if (!(arrayOfHeader[j].getName().equalsIgnoreCase("transfer-encoding")))
        {
          if (arrayOfHeader[j].getName().equalsIgnoreCase("content-length"))
            break label141:
          paramHttpServletResponse.setHeader(arrayOfHeader[j].getName(), arrayOfHeader[j].getValue());
        }
      label141: InputStream localInputStream = localPostMethod.getResponseBodyAsStream();
      if (localInputStream != null)
      {
        ServletOutputStream localServletOutputStream = paramHttpServletResponse.getOutputStream();
        Utils.copyBinaryTo(localInputStream, localServletOutputStream);
      }
    }
    finally
    {
      localPostMethod.releaseConnection();
    }
  }

  private static PostMethod createMethod(HttpServletRequest paramHttpServletRequest, ClusterService paramClusterService1, ClusterService paramClusterService2)
  {
    String str;
    PostMethod localPostMethod = new PostMethod("http://" + paramClusterService1.getIp() + ":" + paramClusterService1.getPort() + "/" + paramClusterService1.getWebAppName() + "/" + FRContext.getConfigManager().getServletMapping());
    Enumeration localEnumeration = paramHttpServletRequest.getParameterNames();
    while (localEnumeration.hasMoreElements())
    {
      str = (String)localEnumeration.nextElement();
      NameValuePair localNameValuePair = new NameValuePair();
      localNameValuePair.setName(str);
      localNameValuePair.setValue(paramHttpServletRequest.getParameter(str));
      localPostMethod.addParameter(localNameValuePair);
    }
    localPostMethod.addParameter("gzip", "false");
    localPostMethod.addParameter("redirect_from", paramClusterService2.getServiceName() + "");
    localEnumeration = paramHttpServletRequest.getHeaderNames();
    while (true)
    {
      while (true)
      {
        while (true)
        {
          do
          {
            if (!(localEnumeration.hasMoreElements()))
              break label264;
            str = (String)localEnumeration.nextElement();
          }
          while (str.equalsIgnoreCase("host"));
          if (!(str.equalsIgnoreCase("refer")))
            break;
        }
        if (!(str.equalsIgnoreCase("content-length")))
          break;
      }
      localPostMethod.setRequestHeader(str, paramHttpServletRequest.getHeader(str));
    }
    label264: return localPostMethod;
  }

  public static boolean CheckCluster(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws IOException
  {
    if ((FRContext.getClusterConfigManager().isUseCluster()) && (VT4FR.SERVER_CLUSTER.support()))
    {
      Object localObject1;
      Object localObject2;
      FRContext.getClusterConfigManager().initClusterServiceConfig(paramHttpServletRequest);
      String str1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "redirect_from");
      if (str1 != null)
        return false;
      String str2 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "cluster_redirect");
      String str3 = null;
      if (str2 != null)
      {
        str3 = str2;
      }
      else
      {
        Object localObject3;
        localObject1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "sessionID");
        localObject2 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "op");
        if (localObject1 != null)
        {
          localObject3 = ((String)localObject1).split("_");
          if (localObject3.length > 0)
            str3 = localObject3[0];
        }
        else if ((localObject2 != null) && (((String)localObject2).startsWith("attach")))
        {
          localObject3 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "id");
          if (localObject3 != null)
          {
            String[] arrayOfString = ((String)localObject3).split("_");
            if (arrayOfString.length > 0)
              str3 = arrayOfString[0];
          }
        }
      }
      if (str3 != null)
      {
        localObject1 = FRContext.getClusterConfigManager().getSelfService();
        if ((localObject1 != null) && (((ClusterService)localObject1).getServiceName().equals(str3)))
          return false;
        localObject2 = FRContext.getClusterConfigManager().getService(str3);
        if (localObject2 != null)
        {
          doRedirect(paramHttpServletRequest, paramHttpServletResponse, (ClusterService)localObject2, (ClusterService)localObject1);
          return true;
        }
      }
    }
    return false;
  }

  private static void clusterTest(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws IOException
  {
    PrintWriter localPrintWriter = paramHttpServletResponse.getWriter();
    localPrintWriter.print("<html>");
    if (FRContext.getClusterConfigManager().isUseCluster())
    {
      localPrintWriter.print("Cluster is start!<br/>");
      ClusterService localClusterService1 = FRContext.getClusterConfigManager().getSelfService();
      if (localClusterService1 != null)
      {
        localPrintWriter.print("SELF:<br/>");
        localPrintWriter.print("ServiceName:" + localClusterService1.getServiceName() + "<br/>");
        localPrintWriter.print("IP:" + localClusterService1.getIp() + "<br/>");
        localPrintWriter.print("PORT:" + localClusterService1.getPort() + "<br/>");
        localPrintWriter.print("WebAppName:" + localClusterService1.getWebAppName() + "<br/>");
        localPrintWriter.print("<br/>");
      }
      else
      {
        localPrintWriter.print("Can not find Own Service Info. <br/>LocalIP:" + FRContext.getClusterConfigManager().getLocalIp() + "<br/>LocalPort:" + FRContext.getClusterConfigManager().getLocalPort() + "<br/>");
      }
      localPrintWriter.print("Other Server List:<br/>");
      List localList = FRContext.getClusterConfigManager().getOtherServices();
      int i = 0;
      while (true)
      {
        if (i >= localList.size())
          break label459;
        ClusterService localClusterService2 = (ClusterService)localList.get(i);
        localPrintWriter.print("NO" + (i + 1) + ": ");
        localPrintWriter.print("ServiceName:" + localClusterService2.getServiceName() + " = " + localClusterService2.getIp() + ":" + localClusterService2.getPort() + "/" + localClusterService2.getWebAppName() + " - ");
        try
        {
          localPrintWriter.print("<font color='green'>" + testOtherClusterService(localClusterService2, "test_cluster") + "</font><br/>");
        }
        catch (IOException localIOException)
        {
          localPrintWriter.print("<font color='red'>" + localIOException.getMessage() + "</font><br/>");
        }
        localPrintWriter.print("<br/><br/>");
        ++i;
      }
    }
    localPrintWriter.print("Cluster is close!<br/>");
    label459: localPrintWriter.print("</html>");
  }

  private static void ClusterTestAll(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws IOException
  {
    PrintWriter localPrintWriter = paramHttpServletResponse.getWriter();
    localPrintWriter.print("<html>");
    if (FRContext.getClusterConfigManager().isUseCluster())
    {
      localPrintWriter.print("Cluster is start<br/>");
      ClusterService localClusterService1 = FRContext.getClusterConfigManager().getSelfService();
      if (localClusterService1 != null)
      {
        localPrintWriter.print("SELF:<br/>");
        localPrintWriter.print("ServiceName:" + localClusterService1.getServiceName() + "<br/>");
        localPrintWriter.print("IP:" + localClusterService1.getIp() + "<br/>");
        localPrintWriter.print("PORT:" + localClusterService1.getPort() + "<br/>");
        localPrintWriter.print("WebAppName:" + localClusterService1.getWebAppName() + "<br/>");
        localPrintWriter.print("<br/>");
      }
      else
      {
        localPrintWriter.print("<font color='red'>");
        localPrintWriter.print("Can not find Own Service Info. LocalIP:" + FRContext.getClusterConfigManager().getLocalIp() + "LocalPort:" + FRContext.getClusterConfigManager().getLocalPort() + "<br/>");
        localPrintWriter.print("</font><br/>");
      }
      localPrintWriter.print("Other Server List:<br/>");
      List localList = FRContext.getClusterConfigManager().getOtherServices();
      int i = 0;
      while (true)
      {
        if (i >= localList.size())
          break label479;
        ClusterService localClusterService2 = (ClusterService)localList.get(i);
        localPrintWriter.print("NO" + (i + 1) + ": ");
        localPrintWriter.print("ServiceName:" + localClusterService2.getServiceName() + " = " + localClusterService2.getIp() + ":" + localClusterService2.getPort() + "/" + localClusterService2.getWebAppName() + "<br/>");
        localPrintWriter.print("------------------------------------------<br/>");
        localPrintWriter.print("Test it(op = cluster_test) - RE:<br/>");
        try
        {
          localPrintWriter.print(testOtherClusterService(localClusterService2, "cluster_test") + "<br/>");
        }
        catch (IOException localIOException)
        {
          localPrintWriter.print(localIOException.getMessage() + "<br/>");
        }
        localPrintWriter.print("------------------------------------------<br/>");
        localPrintWriter.print("<br/><br/><br/><br/>");
        ++i;
      }
    }
    localPrintWriter.print("Cluster is close!<br/>");
    label479: localPrintWriter.print("</html>");
  }

  private static String testOtherClusterService(ClusterService paramClusterService, String paramString)
    throws IOException
  {
    PostMethod localPostMethod = new PostMethod("http://" + paramClusterService.getIp() + ":" + paramClusterService.getPort() + "/" + paramClusterService.getWebAppName() + "/" + FRContext.getConfigManager().getServletMapping());
    localPostMethod.addParameter("op", paramString);
    HttpClient localHttpClient = new HttpClient();
    int i = localHttpClient.executeMethod(localPostMethod);
    if (i != 200)
      return "" + i;
    try
    {
      String str = localPostMethod.getResponseBodyAsString();
      return str;
    }
    finally
    {
      localPostMethod.releaseConnection();
    }
  }

  private static void reClusterTest(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws IOException
  {
    PrintWriter localPrintWriter = paramHttpServletResponse.getWriter();
    localPrintWriter.print("OK");
  }

  public static String getLocalIP()
    throws Exception
  {
    Enumeration localEnumeration1 = NetworkInterface.getNetworkInterfaces();
    InetAddress localInetAddress = null;
    if (localEnumeration1.hasMoreElements())
    {
      NetworkInterface localNetworkInterface = (NetworkInterface)localEnumeration1.nextElement();
      Enumeration localEnumeration2 = localNetworkInterface.getInetAddresses();
      do
      {
        if (!(localEnumeration2.hasMoreElements()));
        localInetAddress = (InetAddress)localEnumeration2.nextElement();
      }
      while ((!(localInetAddress.isSiteLocalAddress())) || (localInetAddress.isLoopbackAddress()) || (localInetAddress.getHostAddress().indexOf(":") != -1));
      return localInetAddress.getHostAddress();
    }
    return null;
  }
}